package com.fan.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fan.reggie.common.BaseContext;
import com.fan.reggie.common.R;
import com.fan.reggie.entity.ShoppingCart;
import com.fan.reggie.service.shoppingCarService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
@Slf4j
public class shoopingCarController {

    @Autowired
    private shoppingCarService shoppingCarService;

    @GetMapping("/list")
    public R<List<ShoppingCart>> list(){
        log.info("查看购物车...");
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        queryWrapper.orderByDesc(ShoppingCart::getCreateTime);

        List<ShoppingCart> shoppingCarts = shoppingCarService.list(queryWrapper);
        return R.success(shoppingCarts);
    }

    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart){
        Long currentId = BaseContext.getCurrentId();
        shoppingCart.setUserId(currentId);
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, currentId);
        //查询菜品或套餐是否在购物车中存在
        Long dishId = shoppingCart.getDishId();
        if(dishId != null){
            //是菜品
            queryWrapper.eq(ShoppingCart::getDishId,dishId);
        }else{
            //是套餐
            queryWrapper.eq(ShoppingCart::getSetmealId, dishId);
        }
        ShoppingCart cart = shoppingCarService.getOne(queryWrapper);
        if(cart !=null){
            //存在，数量加一
            Integer number = cart.getNumber();
            cart.setNumber(number + 1);
            shoppingCarService.updateById(cart);
            return R.success(cart);
        }else {
            //不存在，则添加到购物车
            shoppingCart.setNumber(1);
            shoppingCarService.save(shoppingCart);
            return R.success(shoppingCart);
        }
        //return R.error("点餐出错啦！");
    }

    @DeleteMapping("/clean")
    public R<String> clean(){
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());

        shoppingCarService.remove(queryWrapper);
        return R.success("清空购物车成功");
    }

    @PostMapping("/sub")
    public R<ShoppingCart> sub(@RequestBody ShoppingCart shoppingCart){
        return null;
    }
}
